<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px;">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper" ref="search">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="部门编号">
                <a-input
                  v-model="queryParam.deptId"
                  placeholder="请输入部门编号"
                  allow-clear
                  @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="部门名称">
                <a-input
                  v-model="queryParam.name"
                  placeholder="请输入部门名称"
                  allow-clear
                  @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            <a-col>
              <span class="table-page-search-submitButtons" style="float: right;">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <a-card :bordered="false" class="table-card">

      <sys-dept-add-form
        v-if="showAddModal"
        ref="sysDeptAddForm"
        :deptTypeOptions="deptTypeOptions"
        :statusOptions="statusOptions"
        :deptOptions="deptOptions"
        :expandedKeys="expandedKeys"
        @getTreeselect="getTreeselect"
        @ok="getList"
        @close="showAddModal = false" />

      <sys-dept-edit-form
        v-if="showEditModal"
        ref="sysDeptEditForm"
        :deptTypeOptions="deptTypeOptions"
        :statusOptions="statusOptions"
        :deptOptions="deptOptions"
        :expandedKeys="expandedKeys"
        @getTreeselect="getTreeselect"
        @ok="getList"
        @close="showEditModal = false" />
      <!-- 数据展示 -->
      <advance-table
        :loading="loading"
        title="部门管理"
        rowKey="deptId"
        @refresh="getList"
        :expandIconColumnIndex="1"
        :columns="columns"
        :data-source="list"
        :indentSize="16"
        size="middle"
        tableKey="system-dept-SysDeptIndex-table"
        :defaultExpandedRowKeys="expandedRowKeys"
        :expandedRowKeys="expandedRowKeys"
        :expandIcon="expandIcon"
        @expand="expandNode"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <div class="table-operations" slot="button">
          <a-space align="center">
            <a-button type="primary" @click="handleAdd()" v-hasPerm="['system:dept:add']">
              <a-icon type="plus" />新增
            </a-button>
            <a-button
              type="danger"
              v-if="!multiple"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPerm="['system:dept:remove']">
              <a-icon type="delete" />删除
            </a-button>
          </a-space>
        </div>
        <span slot="name" slot-scope="{text, record}">
          <a-icon v-show="record.deptType === 'org'" class="depIcon" :component="allIcon.companyFillIcon" />
          <a-icon v-show="record.deptType === 'company'" :component="allIcon.companyIcon" class="depIcon" />
          <a-icon v-show="record.deptType === 'dept'" :component="allIcon.connectionsIcon" class="depIcon" />
          <span v-if="text.indexOf(queryParam.name) > -1">
            {{ text.substr(0, text.indexOf(queryParam.name)) }}
            <span style="color: #f50">{{ queryParam.name }}</span>
            {{ text.substr(text.indexOf(queryParam.name) + queryParam.name.length) }}
          </span>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="operation" slot-scope="{record}">
          <a @click="handleUpdate(record)" v-hasPerm="['system:dept:edit']">
            修改
          </a>
          <a-divider type="vertical" v-hasPerm="['system:dept:add']" />
          <a @click="handleAdd(record)" v-hasPerm="['system:dept:add']">
            添加子部门
          </a>
          <a-divider type="vertical" v-if="record.parentId != 0" v-hasPerm="['system:dept:remove']" />
          <a @click="handleDelete(record)" v-if="record.parentId != 0" v-hasPerm="['system:dept:remove']">
            删除
          </a>
        </span>
      </advance-table>
    </a-card>
  </div>
</template>

<script>

import { queryTree, delDept } from '@/api/system/dept'
import SysDeptEditForm from './modules/SysDeptEditForm'
import SysDeptAddForm from './modules/SysDeptAddForm'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import allIcon from '@/core/icons'

export default {
  name: 'Dept',
  components: {
    SysDeptAddForm,
    SysDeptEditForm,
    AdvanceTable,
    allIcon
  },
  data() {
    return {
      showAddModal: false,
      showEditModal: false,
      allIcon,
      list: [],
      // 部门树选项
      deptOptions: [],
      // 状态数据字典
      statusOptions: [],
      expandedKeys: [], // 表单页面默认展开节点
      expandedRowKeys: [], // 树表格展开节点
      selectedRowKeys: [],
      selectedRows: [],
      deptIds: [],
      multiple: true,
      loading: false,
      // 状态数据字典
      deptTypeOptions: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      queryParam: {
        name: undefined,
        deptId: undefined,
        parentId: undefined
      },
      columns: [
        {
          title: '部门编号',
          dataIndex: 'deptId'
        },
        {
          title: '部门名称',
          dataIndex: 'name',
          width: '250px',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '父部门',
          dataIndex: 'parentName',
          width: '250px'
        },
        {
          title: '排序',
          dataIndex: 'treeSort',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '240px',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  filters: {
  },
  created() {
    this.getList()
  },
  computed: {
  },
  watch: {
  },
  methods: {
    expandNode(expanded, record) {
      //  展开收缩时需要动态修改展开行集合
      if (expanded) {
        this.expandedRowKeys.push(record.deptId)
      } else {
        this.expandedRowKeys = this.expandedRowKeys.filter(
          function (item) { return item !== record.deptId }
        )
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.deptIds = this.selectedRows.map(item => item.deptId)
      this.multiple = !selectedRowKeys.length
    },
    /** 查询菜单下拉树结构 */
    getTreeselect(row) {
      if (row) {
        queryTree().then(response => {
          this.deptOptions = response.data
          this.getExpandedKeys(this.deptOptions, 3)
        })
      }
    },
    getExpandedKeys(nodes, expandLevel) {
      if (expandLevel > 1) {
        // 最后一层不展开
        nodes.forEach(node => {
          this.expandedKeys.push(node.id)
          expandLevel = expandLevel - 1
          return this.getExpandedKeys(node.children, expandLevel)
        })
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      queryTree(this.queryParam).then(response => {
        this.expandedRowKeys = []
        // 加载完数据后需要迭代计算需要展开的行数据
        this.expandTree(response.data, 3, this.expandedRowKeys)
        this.list = response.data
        this.loading = false
      }
      )
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        name: undefined,
        deptId: undefined
      }
      this.handleQuery()
    },
    handleAdd(record) {
      this.showAddModal = true
      this.$nextTick(() => (
        this.$refs.sysDeptAddForm.handleAdd(record)
      ))
    },
    handleUpdate(record) {
      this.showEditModal = true
      this.$nextTick(() => (
        this.$refs.sysDeptEditForm.handleUpdate(record)
      ))
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this
      const deptId = row.deptId || this.deptIds
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk () {
          return delDept(deptId).then(() => {
            that.getList()
            that.$message.success(
              '删除成功',
              3
            )
          })
        },
        onCancel() { }
      })
    },
    getAllDeptNode(nodes) {
      if (!nodes || nodes.length === 0) {
        return []
      }
      nodes.forEach(node => {
        this.expandedRowKeys.push(node.deptId)
        return this.getAllDeptNode(node.children)
      })
    },
    expandIcon(props) {
       if (props.record.children.length === 0) {
        return <span style="margin-right:22px"></span>
      } else {
        if (props.expanded) {
          return (
            <a style="color: 'black',margin-right:0px"
              onClick={(e) => {
                props.onExpand(props.record, e)
              }}
            >
              <a-icon type="caret-down" />
            </a>
          )
        } else {
          return (
            <a style="color: 'black' ,margin-right:0px"
              onClick={(e) => {
                props.onExpand(props.record, e)
              }}
            >
              <a-icon type="caret-right" />
            </a>
          )
        }
      }
    }
  }
}
</script>
